import { OSS_BASE_URL } from '@/utils/common';

export const transfromData = (arr, value) => {
  let data = arr.filter(item => item.value == value)
  if (data.length > 0) {
    return data[0].label
  }
  return ''
}

export const transFormValue = (obj) => {
  let arr = [];
  Object.keys(obj).forEach(function (key) {
    if (typeof obj[key] == 'object') {
      if (obj[key] == null) {
        arr.push(`${key}=`)
      } else {
        if (obj[key] == 'object') {
          obj[key] = obj[key].map(item => JSON.stringify(item)).join(',')
        }
        arr.push(`${key}=${JSON.stringify(obj[key])}`)
      }
    } else {
      arr.push(`${key}=${obj[key]}`)
    }
  });
  return '?' + arr.join('&')
}


export const transformData = (data) => {
  let ret = "";
  for (let it in data) {
    if (Array.isArray(data[it])) {
      // 如果是数组，再处理下
      ret += encodeURIComponent(it) + "=" + '[' + data[it].map(item => {
        return encodeURIComponent(JSON.stringify(item))
      }).join(',') + ']' + "&";
    } else {
      ret += encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
    }
  }
  console.log(ret)
  return ret;
}


//点击下载文件名
export const downloadFile = (url, name) => {
  let requestUrl = OSS_BASE_URL + url
  return fetch(requestUrl).then(response => {
    if (!response.ok) {
      throw new Error('network not ok')
    }
    return response.blob();
  }).then(blob => {
    const local_url = window.URL.createObjectURL(blob);
    const elink = document.createElement('a')
    elink.download = name
    elink.style.display = 'none'
    elink.href = local_url
    document.body.appendChild(elink)
    elink.click()
    window.URL.revokeObjectURL(elink.href)// 释放对象
    document.body.removeChild(elink)// 移除元素

  }).catch(error => {
    console.log('error', error)
  })
}

//统一转化城市、区域、街道名称
export const transFromCityName = (cityId, areaId, streetId) => {
  let commonCityList = JSON.parse(localStorage.getItem('city'));
  let city = commonCityList.filter(item => item.id == cityId);
  let cityName = city.length > 0 ? city[0].name : '';
  let area = city[0].areas.filter(item => item.id == areaId);
  let areaName = area.length > 0 ? area[0].name : '';
  let street = area[0].streets.filter(item => item.id == streetId);
  let streetName = street.length > 0 ? street[0].name : '';
  return { cityName, areaName, streetName }
}

export const generateUUID = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}

//树结构数据转化
export const treeTransForm = (arr) => {
  return arr.map(item => {
    let children = null;
    if (item.companies.length > 0) {
      children = treeTransForm(item.companies)
    }
    return { label: item.name, value: item.id, children }
  })
}